import { MciSvgIcon, MciTag, MciTimelineItem, MciTextarea } from '@/components/base';
import { TApprovalStatus, TApprovalTaskItem, useApprovalProvide } from '@/components/business/Approval/approval-helper';
// import { MciRichEditor } from '@/components/complex';
// import { t } from '@/locales';
import { getCSSColor } from '@/utils/color';
import cloneDeep from 'clone-deep';
import { PropType } from 'vue';
import { approvalDateFormat, TTaskStatus } from '.';
type TApprovalUserTaskItem = Required<TApprovalTaskItem>['userTasks'][0];
import { renderCCInfo } from './CCInfo';

export const isApprovalTaskDone = (approvalStatus?: string, endTime?: string) => {
  return !!approvalStatus || !!endTime;
};
// const cloneDeep = require('clone-deep');
// 审批结论文案
const useApprovalResultText = () => {
  const getTypeName = (status: TTaskStatus, approvalStatus?: TApprovalStatus) => {
    if (status === 'INIT') {
      return '提交数据';
    }
    if (status === 'DOING') {
      return '审批中';
    }
    if (status === 'DONE') {
      switch (approvalStatus) {
        case 'AGREE':
        case 'OVERDUE_AGREE':
          return '审批通过';
        case 'DISAGREE':
          return '审批不同意';
        case 'REJECT':
        case 'AUTO_CANCEL':
        case 'OVERDUE_REJECT':
          return '审批驳回';
        default:
          return '未审批';
      }
    }
  };
  return {
    getTypeName
  };
};
// 审批任务节点
export const TaskNode = defineComponent({
  props: {
    data: {
      type: Object as PropType<TApprovalTaskItem | undefined>,
      default: () => {}
    }
  },
  setup(props) {
    const { approvalConclusion } = useApprovalProvide();

    const reject = (approvalStatus: TApprovalStatus) => ['AUTO_CANCEL', 'REJECT'].includes(approvalStatus);
    const disagree = (approvalStatus: TApprovalStatus) => approvalConclusion.value && approvalStatus === 'DISAGREE';
    // 任务状态
    const getTaskStatus = (task?: TApprovalUserTaskItem): TTaskStatus => {
      const data = props.data;
      if (!data) return 'INIT';
      const userTasks = task ? [task] : data.userTasks || [];
      const hasApprovalStatus = userTasks.every((task) => {
        return isApprovalTaskDone(task.approvalStatus, task?.endTime); // 审批结果
      });
      return hasApprovalStatus ? 'DONE' : 'DOING';
    };
    // 用户名，进行中的任务可能有多个
    const getUserName = (task?: TApprovalUserTaskItem) => {
      const data = props.data;
      if (!data) return '';
      const { assigneeUsers } = task || data.userTasks?.[0] || {};
      return assigneeUsers?.map((item) => item.userName || '-').join(' / ');
    };
    // 并行审批
    const isParallel = computed(() => {
      const data = props.data;
      if (!data) return false;
      return !!data.parallel;
    });
    const isReject = computed(() => {
      const userTasks = props.data?.userTasks;
      if (!userTasks) {
        return false;
      }
      let rejected = false;

      let disagreed = false;

      for (const k in userTasks) {
        const approvalStatus = userTasks[k].approvalStatus as TApprovalStatus;
        rejected = reject(approvalStatus);
        if (rejected) break;
      }
      const disagreedCount = userTasks.filter((task) => disagree(task.approvalStatus as TApprovalStatus)).length;
      disagreed = disagreedCount > userTasks.length / 2;

      return rejected || disagreed;
    });

    return {
      getUserName,
      ...useApprovalResultText(),
      getTaskStatus,
      isParallel,
      isReject
    };
  },
  render() {
    const renderBase = () => {
      const currentTask = this.data?.userTasks?.[0];
      const date = currentTask?.endTime || '';
      const approveStatus = currentTask?.approvalStatus as TApprovalStatus;
      const comment = currentTask?.comment || '';
      return (
        <>
          <div class="text-value-14">{this.data?.activityName || ''}</div>
          <div class="text-label-12  mt-4 ">
            {'由'} <span class="text-value-12">{this.getUserName()}</span>{' '}
            {this.getTypeName(this.getTaskStatus(), approveStatus)}
          </div>
          {comment ? (
            <div class="bg-gray-1 mt-8 p-8 rounded-4">
              {/* <MciRichEditor modelValue={comment} mode="view" ellipsis={3} /> */}
              <MciTextarea modelValue={comment} mode="view" ellipsis={3}></MciTextarea>
            </div>
          ) : (
            ''
          )}
          <div class="text-label-12 mt-4">{approvalDateFormat(date)}</div>
        </>
      );
    };
    // 多人并行审批
    const renderParallel = () => {
      const createItem = (task: TApprovalUserTaskItem) => {
        const date = task?.endTime || '';
        const approveStatus = task?.approvalStatus as TApprovalStatus;
        const comment = task?.comment || '';

        // 加签 tag
        const renderAddSignTag = () => {
          if (task.addSignTag) {
            return (
              <MciTag type="info" size="small">
                {task.addSignOperator?.userName ?? ''}
                {'加签'}
              </MciTag>
            );
          }
          return '';
        };
        return (
          <div class="mt-12">
            <div class="text-label-12  mt-4px  flex flex-wrap items-center ">
              <div class="mb-4 mr-4">
                {'由'} <span class="text-value-12">{this.getUserName(task)}</span>{' '}
                {this.getTypeName(this.getTaskStatus(task), approveStatus)}
              </div>
              <div>{renderAddSignTag()}</div>
            </div>
            {comment ? (
              <div class="bg-gray-1 mt-8 p-8 rounded-4">
                {/* <MciRichEditor modelValue={comment} mode="view" ellipsis={3} /> */}
                <MciTextarea modelValue={comment} mode="view" ellipsis={3}></MciTextarea>
              </div>
            ) : (
              ''
            )}
            <div class="text-label-12 mt-4px">{approvalDateFormat(date)}</div>
          </div>
        );
      };
      // 按照 endTime 正序排序
      const sort = () => {
        const getZIndex = (data: TApprovalUserTaskItem) => {
          if (!data.approvalStatus) {
            return Date.now();
          }
          return 0;
        };
        return cloneDeep(this.data?.userTasks || []).sort((a, b) => {
          const timeA = a.endTime ? new Date(a.endTime) : new Date();
          const timeB = b.endTime ? new Date(b.endTime) : new Date();

          const aZIndex = timeA.getTime() + getZIndex(a);
          const bZIndex = timeB.getTime() + getZIndex(b);

          return aZIndex - bZIndex;
        });
      };
      return (
        <>
          <div class="text-value-14">{this.data?.activityName || ''}</div>
          {sort().map(createItem)}
        </>
      );
    };
    const getType = () => {
      const taskStatus = this.getTaskStatus();
      if (taskStatus === 'DOING') {
        return 'warning';
      }
      // 已完成
      return this.isReject ? 'danger' : 'primary';
    };
    const getIcon = () => {
      const taskStatus = this.getTaskStatus();
      const warnIcon = <MciSvgIcon name="progress-wait" width={12} color={getCSSColor('yellow-5')} class="bg-white" />;
      const dangerIcon = <MciSvgIcon name="cross" width={12} color={getCSSColor('yellow-5')} class="bg-white" />;
      if (taskStatus === 'DOING') {
        return warnIcon;
      }
      if (this.isReject) {
        return dangerIcon;
      }
      return 'danger';
    };
    return (
      <MciTimelineItem icon={getIcon()} type={getType()} hollow={true}>
        {this.isParallel ? renderParallel() : renderBase()}
        {renderCCInfo('task', this.data)}
      </MciTimelineItem>
    );
  }
});
